package cn.spream.jstudy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

/**
 * 分布式Lock
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-10-20
 * Time: 下午3:41
 * To change this template use File | Settings | File Templates.
 */
public class DistributedLock {

    private InterProcessMutex interProcessMutex;

    public DistributedLock(CuratorFramework curatorFramework, String path) {
        this.interProcessMutex = new InterProcessMutex(curatorFramework, path);
    }

    public void lock() {
        try {
            interProcessMutex.acquire();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public boolean tryLock() {
        boolean lock = false;
        try {
            lock = interProcessMutex.acquire(0, TimeUnit.SECONDS);
        } catch (Exception e) {
            lock = false;
        }
        return lock;
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        boolean lock = false;
        try {
            lock = interProcessMutex.acquire(time, unit);
        } catch (Exception e) {
            lock = false;
        }
        return lock;
    }

    public void unlock() {
        try {
            if (interProcessMutex.isAcquiredInThisProcess()) {
                interProcessMutex.release();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
